package com.ict.web.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ict.common.utils.SecurityUtils;
import com.ict.common.utils.StringUtils;
import com.ict.common.utils.uuid.IdUtils;
import com.ict.system.service.ISysUserService;
import com.ict.web.constant.ProjectStatusEnum;
import com.ict.web.controller.file.domain.YzqFile;
import com.ict.web.controller.file.dto.YzqFileDTO;
import com.ict.web.controller.file.service.IYzqFileService;
import com.ict.web.domain.Approval;
import com.ict.web.domain.ProjectManagement;
import com.ict.web.domain.SupplementaryDeclaration;
import com.ict.web.dto.ProjectManagementAddDto;
import com.ict.web.dto.SupplementaryDeclarationAddDto;
import com.ict.web.dto.SupplementaryDeclarationEditDto;
import com.ict.web.mapper.SupplementaryDeclarationMapper;
import com.ict.web.service.IApprovalService;
import com.ict.web.service.ISupplementaryDeclarationService;
import com.ict.web.vo.SupplementaryDeclarationVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 增补申报--刘杰Service业务层处理
 *
 * @author ruoyi
 * @date 2022-02-25
 */
@Service
public class SupplementaryDeclarationServiceImpl extends ServiceImpl<SupplementaryDeclarationMapper,SupplementaryDeclaration> implements ISupplementaryDeclarationService
{
    @Resource
    private SupplementaryDeclarationMapper supplementaryDeclarationMapper;

    @Resource
    private ProjectManagementServiceImpl projectManagementService;

    @Resource
    private IYzqFileService fileService;

    @Resource
    private IApprovalService approvalService;

    @Resource
    private ISysUserService userService;

    /**
     * 查询增补申报--刘杰
     *
     * @param supplementaryId 增补申报--刘杰主键
     * @return 增补申报--刘杰
     */
    @Override
    public SupplementaryDeclarationVo selectSupplementaryDeclarationBySupplementaryId(Long supplementaryId)
    {
        SupplementaryDeclaration supplementaryDeclaration =
                supplementaryDeclarationMapper.selectSupplementaryDeclarationBySupplementaryId(supplementaryId);
        SupplementaryDeclarationVo supplementaryDeclarationVo = new SupplementaryDeclarationVo();
        BeanUtils.copyProperties(supplementaryDeclaration,supplementaryDeclarationVo);
        YzqFile file = fileService.getById(supplementaryDeclaration.getSupplementaryVoucher());
        supplementaryDeclarationVo.setSupplementaryVoucherFile(file);
        YzqFile filePp = fileService.getById(supplementaryDeclaration.getProjectProposal());
        supplementaryDeclarationVo.setProjectProposalFile(filePp);
        return supplementaryDeclarationVo;
    }

    /**
     * 查询增补申报--刘杰列表
     *
     * @param supplementaryDeclaration 增补申报--刘杰
     * @return 增补申报--刘杰
     */
    @Override
    public List<SupplementaryDeclaration> selectSupplementaryDeclarationList(SupplementaryDeclaration supplementaryDeclaration)
    {
        return supplementaryDeclarationMapper.selectSupplementaryDeclarationList(supplementaryDeclaration);
    }

    /**
     * 新增增补申报--刘杰
     *
     * @param dto 增补申报--刘杰
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insertSupplementaryDeclaration(SupplementaryDeclarationAddDto dto)
    {
        SupplementaryDeclaration bean = SupplementaryDeclarationAddDto.of(dto);
        //同步文件对象
        ArrayList<YzqFile> fileArrayList = SupplementaryDeclarationAddDto.toFile(bean, dto);
        fileService.batchInsertFile(fileArrayList);
        supplementaryDeclarationMapper.insert(bean);

        //年度申报 添加到 新增项目管理
        ProjectManagementAddDto addDto = new ProjectManagementAddDto();
        //设置 项目名称
        addDto.setName(bean.getEntryName());
        //设置 项目类别
        addDto.setType(bean.getProjectCategory());
        //设置 项目投资估算
        addDto.setInvestmentEstimation(bean.getProjectInvestmentEstimation().setScale(6, BigDecimal.ROUND_HALF_UP));
        //设置 增补申报id
        addDto.setSupplementaryId(bean.getSupplementaryId());
        //设置项目性质:{0:年度项目;1:增补项目;}
        addDto.setNature("1");
        //设置节点 申报审核
        addDto.setNode("-1");
        addDto.setProjectProposal(bean.getProjectProposal());

        if (dto.getTemporaryFlag().equals("1")){ //暂存
            //设置 状态 （未提交）
            addDto.setIsState("-1");

        }else if (dto.getTemporaryFlag().equals("0")){  //提交-不暂存
            //设置 状态 （待审核）
            addDto.setIsState("1");
        }
        projectManagementService.insertProjectManagement(addDto);
        return bean.getSupplementaryId();
    }

    /**
     * 修改增补申报--刘杰
     *
     * @param supplementaryId 增补申报--刘杰
     * @return 结果
     */
    @Override
    public int updateSupplementaryDeclaration(SupplementaryDeclarationEditDto dto,Long supplementaryId)
    {
        SupplementaryDeclaration bean = supplementaryDeclarationMapper.selectById(supplementaryId);
        if (null!=dto.getSupplementaryVoucher() && StringUtils.isNotEmpty(dto.getSupplementaryVoucher().getFileName())  && StringUtils.isNotEmpty(dto.getSupplementaryVoucher().getFileUrl())) {
            //更新文件信息
            YzqFile fileSv = fileService.getById(bean.getSupplementaryVoucher());
            YzqFileDTO fileSvDTO = dto.getSupplementaryVoucher();
            BeanUtils.copyProperties(fileSvDTO,fileSv);
            fileService.updateById(fileSv);
        }
        YzqFile filePp = fileService.getById(bean.getProjectProposal());
        YzqFileDTO filePpDTO = dto.getProjectProposal();
        BeanUtils.copyProperties(filePpDTO,filePp);
        fileService.updateById(filePp);

        BeanUtils.copyProperties(dto, bean);
        bean.setUpdateTime(LocalDateTime.now());

        Long userId = SecurityUtils.getUserId();
        String userName=userService.selectUserById(userId).getUserName();

        //增补申报修改部分同步数据到项目表中
        ProjectManagement projectManagement = projectManagementService.lambdaQuery().eq(ProjectManagement::getSupplementaryId, supplementaryId).one();
        Assert.isTrue(StringUtils.isNotNull(projectManagement),"项目信息未关联该增补申报");
        projectManagement.setName(bean.getEntryName());
        projectManagement.setType(bean.getProjectCategory());
        projectManagement.setInvestmentEstimation(bean.getProjectInvestmentEstimation());
        if ("0".equals(bean.getTemporaryFlag())) {
            Approval approval = approvalService.getApproval(projectManagement.getProId(), projectManagement.getIsState(),null,null);
            if (StringUtils.isNotNull(approval)) {
                approval.setEndTime(LocalDateTime.now());
                approvalService.updateById(approval);
            }else {
                //添加审核提交记录
                approvalService.save(new Approval(IdUtils.snowId(),projectManagement.getProId(),ProjectStatusEnum.DECLARATION_SUBMISSION_SUBMITTED.get().getStage(),
                        ProjectStatusEnum.DECLARATION_SUBMISSION_SUBMITTED.get().getNode(),LocalDateTime.now(),LocalDateTime.now(),SecurityUtils.getNickName(),ProjectStatusEnum.DECLARATION_SUBMISSION_SUBMITTED.get().getStatus(),
                        "/",null, null,null, LocalDateTime.now(),Approval.APPROVAL_TYPE_PROJECT_MANAGE));

            }
            projectManagement.setIsState("1");
            //年度申报

            //保存后提交时添加审核进程
            approvalService.save(new Approval(IdUtils.snowId(),projectManagement.getProId(), ProjectStatusEnum.APPLICATION_REVIEW_TO_BE_REVIEWED.get().getStage(),
                    ProjectStatusEnum.APPLICATION_REVIEW_TO_BE_REVIEWED.get().getNode(),LocalDateTime.now(),null,null,ProjectStatusEnum.APPLICATION_REVIEW_TO_BE_REVIEWED.get().getStatus(),
                    "/",null, null,null, LocalDateTime.now(),Approval.APPROVAL_TYPE_PROJECT_MANAGE));
        }/* else if ("1".equals(bean.getTemporaryFlag())) {
            projectManagement.setIsState("-1");
        }*/
        projectManagementService.updateById(projectManagement);
        return supplementaryDeclarationMapper.updateById(bean);
    }

    /**
     * 删除增补申报--刘杰信息
     *
     * @param supplementaryId 增补申报--刘杰主键
     * @return 结果
     */
    @Override
    public int deleteSupplementaryDeclarationBySupplementaryId(Long supplementaryId)
    {
        SupplementaryDeclaration bean = supplementaryDeclarationMapper.selectById(supplementaryId);
        bean.setDelFlag("1");
        return supplementaryDeclarationMapper.updateById(bean);
    }
}
